import axios from 'axios';
let axiosIns = axios.create({});
const CancelToken = axios.CancelToken;
const source = CancelToken.source();

function postRequest(options) {
    const defaultOptions = {
        method: 'post',
    };
    for (let key in options) {
        if (options.hasOwnProperty(key)) {
            defaultOptions[key] = options[key];
        }
    }
    // 默认请求时间
    axiosIns.defaults.timeout = 2000;
    // 接口根目录
    axiosIns.defaults.baseURL = '';

    // request拦截器，用于验证是否携带token
    axiosIns.interceptors.request.use(
        request => {
            // 接口处理
            return request;
        },
        () => {
            return Promise.reject(new Error({
                errcode: 500,
                errmessage: '接口请求发生错误',
            }));
        },
    );

    // response拦截器，用于处理未验证等极端情况
    axiosIns.interceptors.response.use(
        response => {
            const code = response.data.errcode;
            if (code === 400011) {
                source.cancel();
                return Promise.reject(new Error({
                    errcode: 40001,
                    message: '您还未登录',
                }));
            }
            if (code === 0) {
                return Promise.reject(response.data);
            }
            return Promise.resolve(response);
        },
        err => {
            if (err) {
                const code = err.errcode || err.response.errcode;
                if (code === 40001) {
                    source.cancel();
                }
                return Promise.reject(err);
            }
        },
    );
    return axiosIns
        .request(defaultOptions)
        .then(response => {
            if (response.data && response.data.errcode === 0) {
                return Promise.resolve(response.data);
            } else {
                return Promise.reject(response.data)
            }
        })
        .catch(e => {
            return Promise.reject(e)
        });
}
const http = {
    install(Vue) {
        Vue.prototype.$http = this.$api;
    },
    $api: postRequest,
};
export default http;
